<template>
  <div class="production-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>生产管理</h1>
      <p>生产计划、工单管理、质量控制一站式管理平台</p>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card production-plan">
          <div class="card-content">
            <div class="icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="info">
              <h3>{{ overviewData.totalPlans }}</h3>
              <p>生产计划</p>
              <span class="trend up">+12%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card work-orders">
          <div class="card-content">
            <div class="icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="info">
              <h3>{{ overviewData.activeOrders }}</h3>
              <p>进行中工单</p>
              <span class="trend up">+8%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card equipment">
          <div class="card-content">
            <div class="icon">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="info">
              <h3>{{ overviewData.equipmentEfficiency }}%</h3>
              <p>设备效率</p>
              <span class="trend down">-2%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card quality">
          <div class="card-content">
            <div class="icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="info">
              <h3>{{ overviewData.qualityRate }}%</h3>
              <p>质量合格率</p>
              <span class="trend up">+1.5%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 生产趋势图 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>生产趋势</span>
              <el-select v-model="trendPeriod" size="small" style="width: 120px">
                <el-option label="最近7天" value="7d" />
                <el-option label="最近30天" value="30d" />
                <el-option label="最近90天" value="90d" />
              </el-select>
            </div>
          </template>
          <div ref="productionTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 设备状态分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>设备状态分布</span>
          </template>
          <div ref="equipmentStatusChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工单状态和快捷操作 -->
    <el-row :gutter="20" class="action-section">
      <!-- 工单状态 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card class="work-order-status">
          <template #header>
            <div class="card-header">
              <span>工单状态</span>
              <el-button type="primary" size="small" @click="refreshWorkOrders">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-table :data="workOrderData" style="width: 100%" max-height="300">
            <el-table-column prop="orderNo" label="工单号" width="120" />
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="progress" label="进度" width="120">
              <template #default="scope">
                <el-progress :percentage="scope.row.progress" :stroke-width="8" />
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dueDate" label="预计完成" width="120" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="viewWorkOrder(scope.row)">
                  查看
                </el-button>
                <el-button type="text" size="small" @click="editWorkOrder(scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 快捷操作 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="quick-actions">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="action-buttons">
            <el-button type="primary" class="action-btn" @click="createProductionPlan">
              <el-icon><Plus /></el-icon>
              新建生产计划
            </el-button>
            <el-button type="success" class="action-btn" @click="createWorkOrder">
              <el-icon><DocumentAdd /></el-icon>
              创建工单
            </el-button>
            <el-button type="warning" class="action-btn" @click="scheduleProduction">
              <el-icon><Clock /></el-icon>
              生产排程
            </el-button>
            <el-button type="info" class="action-btn" @click="qualityInspection">
              <el-icon><View /></el-icon>
              质量检验
            </el-button>
            <el-button type="danger" class="action-btn" @click="equipmentMaintenance">
              <el-icon><Tools /></el-icon>
              设备维护
            </el-button>
            <el-button class="action-btn" @click="viewReports">
              <el-icon><DataAnalysis /></el-icon>
              生产报表
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待办事项和通知 -->
    <el-row :gutter="20" class="notification-section">
      <!-- 待办事项 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="todo-card">
          <template #header>
            <span>待办事项</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="item in todoList"
              :key="item.id"
              :timestamp="item.time"
              :type="item.type"
            >
              <div class="todo-item">
                <h4>{{ item.title }}</h4>
                <p>{{ item.description }}</p>
                <el-button type="text" size="small" @click="handleTodo(item)">
                  处理
                </el-button>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <!-- 系统通知 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="notification-card">
          <template #header>
            <span>系统通知</span>
          </template>
          <div class="notification-list">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="notification.type"
            >
              <div class="notification-icon">
                <el-icon v-if="notification.type === 'warning'"><Warning /></el-icon>
                <el-icon v-else-if="notification.type === 'success'"><SuccessFilled /></el-icon>
                <el-icon v-else><InfoFilled /></el-icon>
              </div>
              <div class="notification-content">
                <h4>{{ notification.title }}</h4>
                <p>{{ notification.message }}</p>
                <span class="time">{{ notification.time }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  Calendar,
  Document,
  Setting,
  CircleCheck,
  Refresh,
  Plus,
  DocumentAdd,
  Clock,
  View,
  Tools,
  DataAnalysis,
  Warning,
  SuccessFilled,
  InfoFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const trendPeriod = ref('30d')
const productionTrendChart = ref(null)
const equipmentStatusChart = ref(null)

// 概览数据
const overviewData = reactive({
  totalPlans: 156,
  activeOrders: 89,
  equipmentEfficiency: 87,
  qualityRate: 98.5
})

// 工单数据
const workOrderData = ref([
  {
    id: 1,
    orderNo: 'WO202501001',
    productName: '智能手机主板',
    quantity: 1000,
    progress: 75,
    status: '进行中',
    dueDate: '2025-01-20'
  },
  {
    id: 2,
    orderNo: 'WO202501002',
    productName: '电源适配器',
    quantity: 500,
    progress: 45,
    status: '进行中',
    dueDate: '2025-01-22'
  },
  {
    id: 3,
    orderNo: 'WO202501003',
    productName: '数据线',
    quantity: 2000,
    progress: 100,
    status: '已完成',
    dueDate: '2025-01-18'
  },
  {
    id: 4,
    orderNo: 'WO202501004',
    productName: '保护壳',
    quantity: 800,
    progress: 20,
    status: '待开始',
    dueDate: '2025-01-25'
  }
])

// 待办事项
const todoList = ref([
  {
    id: 1,
    title: '设备维护提醒',
    description: '生产线A需要进行定期维护',
    time: '2025-01-17 09:00',
    type: 'warning'
  },
  {
    id: 2,
    title: '质量检验',
    description: 'WO202501001工单需要质量检验',
    time: '2025-01-17 10:30',
    type: 'primary'
  },
  {
    id: 3,
    title: '物料补充',
    description: '原材料库存不足，需要及时补充',
    time: '2025-01-17 14:00',
    type: 'danger'
  }
])

// 系统通知
const notifications = ref([
  {
    id: 1,
    type: 'warning',
    title: '设备异常',
    message: '生产线B设备温度过高，请及时检查',
    time: '10分钟前'
  },
  {
    id: 2,
    type: 'success',
    title: '工单完成',
    message: 'WO202501003工单已成功完成',
    time: '1小时前'
  },
  {
    id: 3,
    type: 'info',
    title: '计划更新',
    message: '下周生产计划已更新，请查看',
    time: '2小时前'
  }
])

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initProductionTrendChart()
    initEquipmentStatusChart()
  })
}

// 生产趋势图
const initProductionTrendChart = () => {
  if (!productionTrendChart.value) return
  
  const chart = echarts.init(productionTrendChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['计划产量', '实际产量', '合格产量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '计划产量',
        type: 'line',
        data: [1200, 1100, 1300, 1400, 1200, 1500, 1600],
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '实际产量',
        type: 'line',
        data: [1100, 1050, 1250, 1350, 1180, 1450, 1520],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '合格产量',
        type: 'line',
        data: [1080, 1030, 1230, 1320, 1160, 1420, 1490],
        itemStyle: { color: '#E6A23C' }
      }
    ]
  }
  chart.setOption(option)
}

// 设备状态分布图
const initEquipmentStatusChart = () => {
  if (!equipmentStatusChart.value) return
  
  const chart = echarts.init(equipmentStatusChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 45, name: '正常运行', itemStyle: { color: '#67C23A' } },
          { value: 8, name: '维护中', itemStyle: { color: '#E6A23C' } },
          { value: 3, name: '故障', itemStyle: { color: '#F56C6C' } },
          { value: 2, name: '停机', itemStyle: { color: '#909399' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '进行中': 'primary',
    '已完成': 'success',
    '待开始': 'info',
    '已暂停': 'warning',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 事件处理函数
const refreshWorkOrders = () => {
  ElMessage.success('工单数据已刷新')
}

const viewWorkOrder = (row) => {
  router.push(`/production/work-order/${row.id}`)
}

const editWorkOrder = (row) => {
  router.push(`/production/work-order/edit/${row.id}`)
}

const createProductionPlan = () => {
  router.push('/production/planning')
}

const createWorkOrder = () => {
  router.push('/production/work-order/create')
}

const scheduleProduction = () => {
  router.push('/production/scheduling')
}

const qualityInspection = () => {
  router.push('/production/quality')
}

const equipmentMaintenance = () => {
  router.push('/production/equipment')
}

const viewReports = () => {
  router.push('/production/reports')
}

const handleTodo = (item) => {
  ElMessage.info(`处理待办事项：${item.title}`)
}

// 生命周期
onMounted(() => {
  initCharts()
})
</script>

<style scoped>
.production-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.overview-cards {
  margin-bottom: 24px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.card-content .icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.production-plan .icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.work-orders .icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.equipment .icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.quality .icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-content .info h3 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.card-content .info p {
  margin: 0 0 4px 0;
  color: #606266;
  font-size: 14px;
}

.trend {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.trend.up {
  color: #67c23a;
  background-color: #f0f9ff;
}

.trend.down {
  color: #f56c6c;
  background-color: #fef0f0;
}

.charts-section,
.action-section,
.notification-section {
  margin-bottom: 24px;
}

.chart-card,
.work-order-status,
.quick-actions,
.todo-card,
.notification-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  width: 100%;
  height: 40px;
  justify-content: flex-start;
}

.todo-item {
  margin-bottom: 8px;
}

.todo-item h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.todo-item p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #606266;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-icon {
  width: 24px;
  height: 24px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-item.warning .notification-icon {
  color: #e6a23c;
}

.notification-item.success .notification-icon {
  color: #67c23a;
}

.notification-item.info .notification-icon {
  color: #409eff;
}

.notification-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #303133;
}

.notification-content p {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #606266;
}

.notification-content .time {
  font-size: 11px;
  color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .production-dashboard {
    padding: 12px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
  }
  
  .card-content .icon {
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>